<?php

namespace app\common\model\logic;

class ArticleModel
{
    public function __construct()
    {
        $this->curModel = model('dao.article');
    }

    //获取列表方法
    public function getListPage($data)
    {
        $where[] = ['id', '>', 0];
        if (isset($data['keyword']) && !empty($data['keyword'])) {
            $where[] = ['tag', 'like', '%'.$data['keyword'].'%'];
        }
        if (isset($data['category_id']) && $data['category_id'] > 0) {
            $where[] = ['category_id', '=', $data['category_id']];
        }
        $page = getPageData();
        $list = $this->curModel->where($where)->limit($page['start'], $page['limit'])->order('id desc')->all();
        if ($list->isEmpty()) {
            exception(lang('NOT_LIST'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            $category = model('server.article_category');
            foreach ($list as &$ve) {
                $categoryWhere = [];
                $categoryWhere[] = ['id', '=', $ve['category_id']];
                $categoryRow = $category->getLine($categoryWhere);
                $ve['category_name'] = $categoryRow['name'];
            }
            $data['total'] = $this->curModel->where($where)->count();
            $data['list'] = $list;

            return $data;
        }
    }

    //保存添加
    public function saveAdd($data)
    {
        $data['status'] = 1;

        return $this->curModel->allowField(true)->isUpdate(false)->save($data);
    }

    //获取单行
    public function getRow($data)
    {
        $where[] = ['id', '=', $data['id']];
        $row = $this->getLine($where);
        $row['content'] = htmlspecialchars_decode($row['content']);

        return $row;
    }

    //根据条件获取单行
    public function getLine($where)
    {
        $line = $this->curModel->where($where)->findOrEmpty();
        if ($line->isEmpty()) {
            exception(lang('NOT_LIST'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            return $line;
        }
    }

    //保存编辑
    public function saveEdit($data)
    {
        $this->getRow($data);

        return $this->curModel->allowField(true)->isUpdate(true)->save($data);
    }

    //保存删除
    public function saveDel($data)
    {
        $this->getRow($data);
        $result = $this->curModel->destroy($data['id']);
        if ($result !== false) {
            return $result;
        } else {
            exception(lang('DEL_ERROR'), 0, 'app\\common\\exception\\LogicException');
        }
    }
}
